<?php
/*
$Id: ctg-nba-fantasy.php 29 2011-04-01 14:23:22Z eugim.migue@gmail.com $
*/

require_once 'quickstart-loading-re.php';

function compile_player_stats($players, $heading){

	$_players = array();
	$types      = array_values($heading);
	
	foreach($players as $player){
	
		$player_info = array();
		$player = explode('	', $player);
		$cut_str_position = 1+strpos ($player[0], ')');
		$player_info[0] = substr($player[0], 0, $cut_str_position);
		$counter = 1;
		//echo count($player).'<br>';
		if(count($player) == 17)
		   $start_count = 8;
		elseif(count($player) == 16)
		   $start_count = 7;
		elseif(count($player) == 14)
		   $start_count = 5;
		else
			$start_count = 6;
		
		for($i = $start_count; $i<count($player); $i++){
			
			  settype($player[$i], $types[$counter]);
			  $player_info[$counter] = $player[$i];
			  $counter++;
		}
		$_players[] = array_combine(array_keys($heading), $player_info);
	}
	
	return $_players;
}

function create_data_table($relation, $summary = array(), $column_ordering = array()){

	$table = '<table class="inputPlayer" width="100%" border="1"><thead><tr>';
	foreach($column_ordering as $n){
		$table .= '<td width="55%">' . $n . '</td>';
	}
	$table .= '</tr></thead><tbody>';
	  
  
	foreach($relation->toArray() as $tuple){
		$_td = array();
		foreach($column_ordering as $n){
			$_td[] = "<td>" . $tuple->get($n) . "</td>";
		}
		$table .= "<tr>" . implode("",$_td) . "</tr>";
	}
  
	
	if( !empty($summary) || (!is_array($summary) && $summary instanceof re_Relation) ){
		foreach($summary->toArray() as $tuple){
			$_td = array();
			foreach($column_ordering as $n){
				$v = $tuple->get($n);
				$_td[] = "<td>" . (is_double($v) ? number_format($v, 3) : $v) . "</td>";
			}
			$table .= "<tr>" . implode("",$_td) . "</tr>";	
		}
	}
	$table .= "</tbody></table>";
	return $table;
}

function compute_evaluation($you, $opp){
	
	$r = re::relation(array(), array('STAT'=>'string', 'YOU'=>'string', 'OPP'=>'string'));
	foreach($you->heading() as $n=>$t){
	
		$_y = $you->get($n) - $opp->get($n);
		
		$y = $_y < 0 ? "-" : $_y;
		$o = $_y > 0 ? "-" : abs($_y);
		
		$r = $r->union(re::relation(array(
			array('STAT'=>$n, 'YOU'=>"$y", 'OPP'=>"$o")
		)));
	}
	return $r;	
}

$is_result = isset($_POST['btnCalculate']);
if( $is_result ){

	$players_heading = array(
		'Player'=>'string'
	   ,'FG'=>'double'
	   ,'FT'=>'double'
	   ,'3PT'=>'double'
	   ,'PTS'=>'double'
	   ,'Rebs'=>'double'
	   ,'Ast'=>'double'
	   ,'Stl'=>'double'
	   ,'Blk'=>'double'
	   ,'TO'=>'double'
	);
	
	$players_owned    = re::relation(compile_player_stats($_POST['txtPlayer'], $players_heading), $players_heading);
	$players_opposed = re::relation(compile_player_stats($_POST['txtPlayer2'], $players_heading), $players_heading);	
	
	$summary = array(
		'_FG'=>array('AVG', array('FG'))
	   ,'_FT'=>array('AVG', array('FT'))
	   ,'_3PT'=>array('SUM', array('3PT'))
	   ,'_PTS'=>array('SUM', array('PTS'))
	   ,'_REBS'=>array('SUM', array('rebs'))
	   ,'_AST'=>array('SUM', array('ast'))
	   ,'_STL'=>array('SUM', array('stl'))
	   ,'_BLK'=>array('SUM', array('blk'))
	   ,'_TO'=>array('SUM', array('to'))
	);	
	
	$players_owned_summ    = $players_owned->summarizeAll($summary)->rename(array(array("", "_")))->extend(array('Player'=>'Total'));
	$players_opposed_summ = $players_opposed->summarizeAll($summary)->rename(array(array("", "_")))->extend(array('Player'=>'Total'));
	
	$evaluation = $players_owned_summ->project(array('player'), TRUE)->extend(array(
		'EVALUATION'=>'compute_evaluation'
	), array(
		'EVALUATION'=>array('args'=>($players_opposed_summ->project(array('player'), TRUE)->toTuple()))
	))->toTuple()->get('EVALUATION');	
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My NBA Fantasy Calculator</title>

<script language="javascript" type="text/javascript" src="misc-files/addrow.js"></script>
<link href="misc-files/style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div class="body-wrapper">
  <div class="header-wrapper"> 
  </div>
  <div class="content-wrapper">
     <div class="main-column">
		<?php
			if( FALSE == $is_result ){
		?>
         <h1>My NBA Fantasy Calculator</h1>
		 
         <div class="howto-box"><strong><u>How to Use</u></strong>: <br />
			<ol>
               <li>Go to "<strong>My Team</strong>" or your opponents &quot;<strong>Team</strong>&quot; then click on the <strong>Avg. Stats</strong> to view  the average stats of the player.</li>
               <li>To select a player, hold Ctrl (for windows) or Cmd (for mac) then start from the right most side of the player stats row. Click and hold left click of mouse then drag your mouse all the way to the players name. <br />
				(<em>If you did it correctly you will notice the selection will be in boxes and it does not highlight some of the text</em>. <strong><em>Switch to &quot;Classic&quot; view when you're selecting your team. It's located at the top right corner of the player stats</em>.</strong>)</li>
               <li>Copy then paste the stats on the player box.</li>
               <li>Click the &quot;+&quot; button to add more players and the &quot;-&quot; button to remove the latest player added.</li>
            </ol>
            <i>*** Don't leave the player text box blank when you calculate; You can also use the trade proposal view and click on the avg. stats view. </i>
         </div>
         <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="frmCalc" >
         <div class="left-column">
            <h3>Your Players</h3>
                <table width="100%" id="tblTeam" class="inputPlayer">
                  <tr>
                    <td width="120">Player 1</td>
                    <td width="364"><label>
                      <textarea name="txtPlayer[]" id="txtOwnPlayer1" cols="45" rows="5"></textarea>
                    </label></td>
                  </tr>
                </table>
                <input name="btnAddRow" type="button" value="+"  onclick="addRowToTable('tblTeam');"  />
                <input name="btnRemoverow" type="button" value="-" onclick="removeRowFromTable('tblTeam');"  />
                <br />
				<br />
				<input name="btnCalculate" type="submit" value="Calculate" />
                </div>
         
         <div class="right-column">
            <h3>Opposing Players</h3>
                <table width="100%" id="tblTeam2" class="inputPlayer">
                  <tr>
                    <td width="114">Player 1</td>
                    <td width="370"><label>
                      <textarea name="txtPlayer2[]" id="txtOppPlayer1" cols="45" rows="5"></textarea>
                    </label></td>
                  </tr>
                </table>
                 <input name="btnAddRow" type="button" value="+"  onclick="addRowToTable('tblTeam2');"  />
                <input name="btnRemoverow" type="button" value="-" onclick="removeRowFromTable('tblTeam2');"  /> 
         </div>
        
          </form>
        <?php
			}
			else{		
		?>
			  <h1>Results</h1>
			  <div class="left-column">
				<h3>Your Players Stats</h3>
				<?php echo create_data_table($players_owned,  $players_owned_summ, array_keys($players_heading)); ?>
			  </div>
			
			  <div class="right-column">
				<h3>Opposing Players Stats</h3>
			 	<?php echo create_data_table($players_opposed,  $players_opposed_summ, array_keys($players_heading)); ?>
			  </div>
			  <div class="summaryTable">
				 <div class="left-column" style="width:250px;" >
				 <h4>Trade Stat Evaluation</h4>
				 <?php echo create_data_table($evaluation, array(), array('Stat', 'You', 'Opp')); ?> 	
				 </div>
				 <div class="right-column">
				 <p>You lead in <?php echo $evaluation->semiminus(re::relation(array(array('you'=>'-'))))->count(); ?> categories. &nbsp;</p>
				 <p>Your opponent leads in <?php echo $evaluation->semiminus(re::relation(array(array('opp'=>'-'))))->count(); ?> categories.</p>
				 </div>
			  </div>			  
		<?php
			}
		?>
     </div>
  </div>
  
  <div class="footer-wrapper">
  </div>
</div>
</body>
</html>